// mouse-handler.js —— 拖拽方向完全正确 + X/Y 轴互不干扰
import { view } from './view-state.js';
import { xToFreq, AXIS_LEFT, AXIS_BOTTOM } from './canvas-utils.js';

let isDragging = false;
let dragStart = { x: 0, y: 0 };
let viewStart = {};

export function setupMouseHandlers(canvas) {
    // 滚轮缩放（你之前的已经很好了，保持不动）
    canvas.addEventListener('wheel', e => {
        e.preventDefault();
        const dpr = window.devicePixelRatio || 1;
        const rect = canvas.getBoundingClientRect();

        const x = (e.clientX - rect.left) * dpr;
        const y = (e.clientY - rect.top) * dpr;
        const delta = e.deltaY > 0 ? 1.15 : 0.87;

        // 自动判断轴（你已经很完美了，保持）
        const inLeftAxis  = x < AXIS_LEFT;
        const inBottomAxis = y > canvas.height - AXIS_BOTTOM;

        if (inLeftAxis || (!inBottomAxis && !e.ctrlKey && !e.metaKey)) {
            // Y轴缩放
            const plotH = canvas.height - AXIS_BOTTOM;
            const ratioY = y / plotH;
            const dbUnderMouse = view.maxDb - ratioY * (view.maxDb - view.minDb);
            const oldRange = view.maxDb - view.minDb;
            const newRange = oldRange * delta;
            view.minDb = dbUnderMouse - ratioY * newRange;
            view.maxDb = dbUnderMouse + (1 - ratioY) * newRange;
        } else {
            const plotW = canvas.width - AXIS_LEFT;
            const freqUnderMouse = xToFreq(x, canvas, view);
            const oldLeft = view.centerFreq - view.bandwidth / 2;
            const newBw = view.bandwidth * delta;
            const newLeft = freqUnderMouse - (freqUnderMouse - oldLeft) * (newBw / view.bandwidth);
            view.bandwidth = newBw;
            view.centerFreq = newLeft + newBw / 2;
        }
        window.redrawAll();
    });

    // ==================== 拖拽平移（重点修复）====================
    canvas.addEventListener('pointerdown', e => {
        if (e.button !== 0) return;
        const dpr = window.devicePixelRatio || 1;
        const rect = canvas.getBoundingClientRect();

        const mouseX = (e.clientX - rect.left) * dpr;
        const mouseY = (e.clientY - rect.top) * dpr;

        const inLeftAxis   = mouseX < AXIS_LEFT;
        const inBottomAxis = mouseY > (canvas.height - AXIS_BOTTOM);

        dragStart = {
            x: mouseX,
            y: mouseY,
            mode: e.shiftKey ? 'freq' :
                inBottomAxis ? 'freq' :
                    inLeftAxis ? 'db' : 'db'
        };
        viewStart = { ...view };
        isDragging = true;
        canvas.setPointerCapture(e.pointerId);
    });

    canvas.addEventListener('pointermove', e => {
        if (!isDragging) return;

        const dpr = window.devicePixelRatio || 1;
        const rect = canvas.getBoundingClientRect();

        const currentX = (e.clientX - rect.left) * dpr;
        const currentY = (e.clientY - rect.top) * dpr;

        const dx = currentX - dragStart.x;
        const dy = currentY - dragStart.y;

        if (dragStart.mode === 'freq') {
            // 【反向】向右拖 → 中心频率变小（你想要的）
            const pixelsPerMHz = (canvas.width - AXIS_LEFT) / view.bandwidth;
            view.centerFreq = viewStart.centerFreq - dx / pixelsPerMHz;   // 关键：减号！
        } else {
            // 【反向】向上拖（dy < 0）→ 看到更弱信号 → dB 范围整体减小
            const pixelsPerDb = (canvas.height - AXIS_BOTTOM) / (view.maxDb - view.minDb);
            const deltaDb = dy / pixelsPerDb;   // 关键：加号！（dy < 0 时 deltaDb < 0 → 范围下移）
            view.minDb = viewStart.minDb + deltaDb;
            view.maxDb = viewStart.maxDb + deltaDb;
        }

        window.redrawAll();
    });

    ['pointerup', 'pointercancel', 'pointerleave'].forEach(ev => {
        canvas.addEventListener(ev, () => { isDragging = false; });
    });

    // 双击复位
    canvas.addEventListener('dblclick', () => {
        Object.assign(view, {
            minDb: -120,
            maxDb: 0,
            centerFreq: parseFloat(document.getElementById('centerFreq').value) || 255,
            bandwidth: parseFloat(document.getElementById('bandwidth').value) || 40
        });
        window.redrawAll();
    });
}